var express = require('express');
var router = express.Router();
const jwt = require('jsonwebtoken');
const { verifyToken, judgeToken, decodeToken } = require('../../tool/jwt')
const { setDate } = require('../../tool/date')

const fs = require('fs');
const querystring = require('querystring');

const {getImageAuditing,uploadImage,deleteImage} = require('../../tool/ImageAudit')

const multer = require('multer');
// 配置multer
const storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, 'public/img/') // 定义上传的文件夹
    },
    filename: function (req, file, cb) {
        cb(null, file.fieldname + '-' + Date.now() + '.' + file.originalname.split('.').pop())
    }
});

const upload = multer({ storage: storage });

//引入支付宝沙箱配置
const alipaySdk = require('../../tool/alipay');
const AlipayFormData = require('alipay-sdk/lib/form').default;

//验证token方法
const tokenvalidate = (req, res, next) => {
    try {
        const token = req.headers.token;
        const v = verifyToken(token, 'shop_key')

        if (v != null) {
            const v2 = judgeToken(token, 'shop_key')

            if (v2 == 0) {
                next()
            } else {

                return res.send({ data: { msg: 'token已过期', code: '500' } })
            }

        } else {
            return res.send({ data: { msg: 'token已过期', code: '500' } })
        }

    } catch (error) {
        console.log(error)
        res.status(500).send('Error');
        process.exit(1)
    }
}

module.exports = (pool) => {

    //获取商品分类
    router.get('/getShopType', (req, res, next) => { tokenvalidate(req, res, next) }, async (req, res) => {
        try {
            const connection = await pool.promise().getConnection();
            const result = await connection.query('select * from classify')
            connection.release();
            res.send({ data: { msg: '获取成功', code: 200, data: result[0] } })
        } catch (error) {
            console.error(error);
            res.status(500).send({ data: { msg: "服务异常", code: 500 } });
            process.exit(1)
        }
    })

    //获取商品列表
    router.get('/getShopList', (req, res, next) => { tokenvalidate(req, res, next) }, async (req, res) => {
        try {
            const connection = await pool.promise().getConnection();
            const result = await connection.query('select goods.*,user.avatar,user.nickname from goods join user on goods.uid = user.id where goods.state = 1')
            connection.release();
            res.send({ data: { msg: '获取成功', code: 200, data: result[0] } })
        } catch (error) {
            console.error(error);
            res.status(500).send({ data: { msg: "服务异常", code: 500 } });
            process.exit(1)
        }
    })
    //获取商品详情
    router.get('/getShopDetail/:id', (req, res, next) => { tokenvalidate(req, res, next) }, async (req, res) => {
        try {
            const { id } = req.params
            const connection = await pool.promise().getConnection();
            const result = await connection.query('select goods.*,user.avatar,user.nickname from goods join user on goods.uid = user.id where goods.id = ? and goods.state = 1', [id])
            const result2 = await connection.query('select reviews.*,user.avatar from reviews join user on user.id = reviews.uid where reviews.gid = ? and reviews.state = 1', [id])
            connection.release();
            res.send({ data: { msg: '获取成功', code: 200, data: result[0][0] ,review:result2[0]} })
        } catch (error) {
            console.error(error);
            res.status(500).send({ data: { msg: "服务异常", code: 500 } });
            process.exit(1)
        }
    })
    //商品留言
    router.post('/shopMessage', (req, res, next) => { tokenvalidate(req, res, next) }, async (req, res) => {
        try {
            const {  gid, content } = req.body
            // 获取用户信息
            const user = decodeToken(req.headers.token);
            if (user == null) return res.send({ data: { msg: 'token已过期', code: 500 } });
            const connection = await pool.promise().getConnection();
            const result = await connection.query('insert into reviews (gid,content,create_data,uid) values (?,?,?,?)', [gid, content, setDate(),user.id])
            connection.release();
            if(result[0].affectedRows == 1){
                res.send({ data: { msg: '留言成功', code: 200 } })
            }else{
                res.send({ data: { msg: '留言失败', code: 500 } })
            }
        } catch (error) {
            console.error(error);
            res.status(500).send({ data: { msg: "服务异常", code: 500 } });
            process.exit(1)
        }
    })

    //咨询商品--创建聊天
    router.post('/createChat', (req, res, next) => { tokenvalidate(req, res, next) }, async (req, res) => {
        try {
            // 获取用户信息
            const user = decodeToken(req.headers.token);
            if (user == null) return res.send({ data: { msg: 'token已过期', code: 500 } });
            const { uid, gid } = req.body
            const connection = await pool.promise().getConnection();
            const result1 = await connection.query('select id from newslist where uid_buy = ? or uid_sell = ? and gid = ?', [user.id, user.id, gid])
            if (result1[0].length > 0) {
                connection.release();
                return res.send({ data: { msg: '已创建聊天', code: 200, data: result1[0][0] } })
            }
            const result2 = await connection.query('insert into newslist (uid_buy,gid,uid_sell,create_date) values (?,?,?,?)', [user.id, req.body.gid, uid, setDate()])
            connection.release();
            res.send({ data: { msg: '创建成功', code: 200, data: { id: result2[0].insertId } } })
        } catch (error) {
            console.error(error);
            res.status(500).send({ data: { msg: "服务异常", code: 500 } });
            process.exit(1)
        }
    })

    //创建订单 -- 支付宝支付
    router.post('/createOrder', (req, res, next) => { tokenvalidate(req, res, next) }, async (req, res) => {
        try {
            const { gid, zong, receiverPhone, receiverName, address } = req.body
            // 获取用户信息
            const user = decodeToken(req.headers.token);
            if (user == null) return res.send({ data: { msg: 'token已过期', code: 500 } });
            const connection = await pool.promise().getConnection();
            //订单状态，0待付款、1已付款、2待发货、3已发货、4已完成、5已取消
            const result = await connection.query('insert into orders (uid,gid,order_amount,receiver_phone,receiver_name,shipping_address,order_time,order_status) values (?,?,?,?,?,?,?,?)', [user.id, gid, zong, receiverPhone, receiverName, address, setDate(), 0])
            connection.release();
            const formData = new AlipayFormData();
            //调用get方法
            formData.setMethod('get'),
                //支付时 的信息
                formData.addField('bizContent', {
                    outTradeNo: result[0].insertId,//订单号
                    productCode: 'FAST_INSTANT_TRADE_PAY',//固定
                    totalAmount: zong,//金额
                    subject: '商品名称'//商品名称
                });

            formData.addField('notifyUrl', 'http://edrwuk.natappfree.cc/shop/payment/callback');
            //支付成功或者失败打开的页面
            formData.addField('returnUrl', 'http://localhost:3000');
            const result2 = alipaySdk.exec(
                'alipay.trade.page.pay',
                {},
                { formData: formData },
            );
            result2.then(resp => {
                res.send({
                    data: {
                        code: 200,
                        success: true,
                        order: result[0].insertId,
                        paymentUrl: resp
                    }
                })
            })

        } catch (error) {
            console.error(error);
            res.status(500).send({ data: { msg: "服务异常", code: 500 } });
            process.exit(1)
        }
    })
    //支付成功回调
    router.post("/payment/callback", async (req, res) => {
        try {
            const paymentResult = req.body;
            
            if (paymentResult.trade_no) {
                const connection = await pool.promise().getConnection()
                await connection.query(`UPDATE orders SET order_status=?,payment_time=? WHERE id = ?`, [1, setDate(),paymentResult.out_trade_no])
                connection.release();
                res.send({ data: { msg: '支付成功', code: 200 } });
            } else {
                res.send({ data: { msg: '支付失败', code: 500 } });
            }
        } catch (error) {
            console.error(error);
            res.status(500).send({ data: { msg: "服务异常", code: 500 } });
            process.exit(1)
        }
    })

    //查看订单支付状态
    router.get('/orderStatus/:order_id', (req, res, next) => { tokenvalidate(req, res, next) }, async(req,res)=>{
        try {
            const {order_id} = req.params
            const connection = await pool.promise().getConnection()
            const result = await connection.query(`SELECT order_status FROM orders WHERE id = ?`,[order_id])
            connection.release();
            if(result[0][0].order_status == 1){
                res.send({data:{msg:'支付成功',code:200}})
            }else{
                res.send({data:{msg:'支付失败',code:500}})
            }
        } catch (error) {
            console.error(error);
            res.status(500).send({ data: { msg: "服务异常", code: 500 } });
            process.exit(1)
        }
    })

    //商品分类查询
    router.get('/getShopListByType/:cid',(req, res, next) => { tokenvalidate(req, res, next) },async(req,res)=>{
        try {
            const {cid} = req.params
            const connection = await pool.promise().getConnection();
            const result = await connection.query('select goods.*,user.avatar,user.nickname from goods join user on goods.uid = user.id where goods.state = 1 and goods.class_id =?',[cid])
            connection.release();
            res.send({ data: { msg: '获取成功', code: 200, data: result[0] } })
        } catch (error) {
            console.error(error);
            res.status(500).send({ data: { msg: "服务异常", code: 500 } });
            process.exit(1)
        }
    })
    //商品搜索
    router.post('/getShopListByinfo',(req, res, next) => { tokenvalidate(req, res, next) },async(req,res)=>{
        try {
            const {gname} = req.body
            const connection = await pool.promise().getConnection();
            const result = await connection.query(`select goods.*,user.avatar,user.nickname from goods join user on goods.uid = user.id where goods.state = 1 and goods.description like '%${gname}%'`,[])
            connection.release();
            res.send({ data: { msg: '获取成功', code: 200, data: result[0] } })
        } catch (error) {
            console.error(error);
            res.status(500).send({ data: { msg: "服务异常", code: 500 } });
            process.exit(1)
        }
    })
    //文件上传
    router.post('/upload', upload.single('uploadFile'), async(req, res) => {
        console.log(req.file); // 输出文件信息

        try {
            const result = await uploadImage(`public/img/${req.file.filename}`,req.file.filename)
            console.log(result)
            if (result) {
                res.send({ data: { msg: '上传成功', code: 200, data: `http://localhost:3000/img/${req.file.filename}` } });
            }else {
                fs.unlink(`public/img/${req.file.filename}`,(err) => {
                    if (err) {
                      console.error('删除文件出错:', err);
                      return;
                    }
                    console.log('文件已成功删除');
                })
                deleteImage(req.file.filename)
                res.send({ data: { msg: '上传失败', code: 500, data: `http://localhost:3000/img/${req.file.filename}` } });
            }
        } catch (error) {
            console.error(error);
            res.status(500).send({ data: { msg: "服务异常", code: 500 } });
            process.exit(1)
        }
        
    });
    //商品发布
    router.post('/publish',(req, res, next) => { tokenvalidate(req, res, next) },async(req,res)=>{
        try {
            const {url,price,description,class_id,condition,shippingMethod,shippingCost} = req.body
             // 获取用户信息
             const user = decodeToken(req.headers.token);
             if (user == null) return res.send({ data: { msg: 'token已过期', code: 500 } });
            const connection = await pool.promise().getConnection();
            
            const result = await connection.query('insert into goods(url,price,description,class_id,uid,`condition`,shipping_method,shipping_cost,created_at,state) values(?,?,?,?,?,?,?,?,?,?)',[url,price,description,class_id,user.id,condition,shippingMethod,shippingCost,setDate(),1])
            connection.release();
            if(result[0].affectedRows == 1){
                res.send({ data: { msg: '发布成功', code: 200 } })
            }else{
                res.send({ data: { msg: '发布失败', code: 500 } })
            }
        } catch (error) {
            console.error(error);
            res.status(500).send({ data: { msg: "服务异常", code: 500 } });
            process.exit(1)
        }
    })
    //进程崩溃，关闭数据库连接
    process.on('SIGINT', () => {
        pool.end();
        redis.disconnect();
        process.exit(0);
    })
    return router;
}